package mq

import (
	"im-mq/db"
	"log"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func mqtt_auth(c *gin.Context) {
	return
}

func mqtt_acl(c *gin.Context) {
	//strIpAddr := c.DefaultQuery("ipaddr", "")
	strTopic := c.DefaultQuery("topic", "")

	if c.MustGet("AuthCheck") == "1" {
		if strings.HasPrefix(strTopic, "$") || strings.HasPrefix(strTopic, "#") ||
			strings.HasPrefix(strTopic, "+") {
			c.JSON(http.StatusForbidden, gin.H{
				"code": 403,
				"msg":  "Failed",
			})
			return
		}
	}
}

func mq_auth_middleware(c *gin.Context) {
	var strUname string
	var strCid string
	if c.Request.Method == "POST" {
		strUname = c.DefaultPostForm("username", "")
		strCid = c.DefaultPostForm("clientid", "")
		log.Println(c.Request.Method, c.Request.URL.Path, strUname, strCid)
	} else {
		strUname = c.DefaultQuery("username", "")
		strCid = c.DefaultQuery("clientid", "")
	}

	// normal auth
	if len(strUname) > 0 && db.Session_Get(strCid) == strUname {
		c.Set("AuthCheck", "1")
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "ok",
		})
	} else {
		c.Set("AuthCheck", "0")
		c.JSON(http.StatusForbidden, gin.H{
			"code": 403,
			"msg":  "Failed",
		})
	}
}
func Init_Once(app *gin.Engine) {
	mqApp := app.Group("/mqtt")
	mqApp.Use(mq_auth_middleware)

	mqApp.POST("/auth", mqtt_auth)
	//mqApp.POST("/superuser", mqtt_auth)
	mqApp.GET("/acl", mqtt_acl)

}
